package com.uduemc.biso.node.module.controller;

import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.entities.SEmail;
import com.uduemc.biso.node.module.service.SEmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/s-email")
public class SEmailController {

	private static final Logger logger = LoggerFactory.getLogger(SEmailController.class);

	@Autowired
	private SEmailService sEmailService;

	@PostMapping("/insert")
	public RestResult insert(@Valid @RequestBody SEmail sEmail, BindingResult errors) {
		logger.info("insert: " + sEmail.toString());
		if (errors.hasErrors()) {
			Map<String, Object> message = new HashMap<>();
			for (FieldError fieldError : errors.getFieldErrors()) {
				String field = fieldError.getField();
				String defaultMessage = fieldError.getDefaultMessage();
				message.put(field, defaultMessage);
			}

			return RestResult.error(message);
		}
		SEmail data = sEmailService.insert(sEmail);
		return RestResult.ok(data, SEmail.class.toString());
	}

	@PostMapping("/insert-batch")
	public RestResult insert(@Valid @RequestBody List<SEmail> emailList, BindingResult errors) {
		logger.info("insertBatch: " + emailList.toString());
		if (errors.hasErrors()) {
			Map<String, Object> message = new HashMap<>();
			for (FieldError fieldError : errors.getFieldErrors()) {
				String field = fieldError.getField();
				String defaultMessage = fieldError.getDefaultMessage();
				message.put(field, defaultMessage);
			}

			return RestResult.error(message);
		}
		List<SEmail> sEmailList = sEmailService.insert(emailList);
		return RestResult.ok(sEmailList, SEmail.class.toString(), true);
	}

	@PostMapping("/update")
	public RestResult update(@Valid @RequestBody SEmail sEmail, BindingResult errors) {
		logger.info("update: " + sEmail.toString());
		if (errors.hasErrors()) {
			Map<String, Object> message = new HashMap<>();
			for (FieldError fieldError : errors.getFieldErrors()) {
				String field = fieldError.getField();
				String defaultMessage = fieldError.getDefaultMessage();
				message.put(field, defaultMessage);
			}

			return RestResult.error(message);
		}
		SEmail data = sEmailService.update(sEmail);
		return RestResult.ok(data, SEmail.class.toString());
	}

	@GetMapping("/get-email-list/{start:\\d+}/{count:\\d+}")
	public RestResult getEmailList(@PathVariable("start") Integer start, @PathVariable("count") Integer count) {
		logger.info("getEmailList count:" + count);
		List<SEmail> findAll = sEmailService.getEmailList(start, count);
		return RestResult.ok(findAll, SEmail.class.toString(), true);
	}
}